package com.weiaibenpao.demo.chislim.hurui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.easeui.domain.EaseUser;
import com.hyphenate.easeui.ui.EaseContactListFragment;
import com.hyphenate.easeui.ui.EaseConversationListFragment;
import com.weiaibenpao.demo.chislim.R;
import com.weiaibenpao.demo.chislim.hurui.base.HBaseFragment;
import com.weiaibenpao.demo.chislim.hurui.huanxin.Constant;
import com.weiaibenpao.demo.chislim.hurui.huanxin.DemoHelper;
import com.weiaibenpao.demo.chislim.hurui.huanxin.activity.AddContactActivity;
import com.weiaibenpao.demo.chislim.hurui.huanxin.activity.ChatActivity;
import com.weiaibenpao.demo.chislim.hurui.huanxin.activity.GroupsActivity;
import com.weiaibenpao.demo.chislim.hurui.huanxin.activity.NewFriendsMsgActivity;
import com.weiaibenpao.demo.chislim.hurui.huanxin.fragment.ContactListFragment;

import java.util.Hashtable;
import java.util.List;
import java.util.Map;

import butterknife.BindView;


/**
 * Created by lenovo on 2017/4/14.
 */

public class HR_Fouth_Fragment extends HBaseFragment {
    private int num  = 0;

    private FragmentManager fm ;

    private View rootView ;

    private EaseConversationListFragment easeConversationListFragment ;
    private ContactListFragment easeContactListFragment ;

    @BindView(R.id.segmented2)
    RadioGroup segmented2 ;

    @Override
    public View onCreateView(LayoutInflater inflater,  ViewGroup container,  Bundle savedInstanceState) {
        if(rootView == null){
            rootView = inflater.inflate(R.layout.hr_fouth_fragment, null , false);
            fm = getActivity().getSupportFragmentManager();
            initFragment1();
            initChatListen();
        }
        return rootView;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        segmented2.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if(checkedId == R.id.button21){
                    num = 0 ;
                    initFragment1();
                }else if(checkedId == R.id.button22){
                    num = 1 ;
                    initFragment2();
                }
            }
        });
    }


    //显示第一个fragment
    private void initFragment1(){

        FragmentTransaction transaction = fm.beginTransaction();

        if(easeConversationListFragment == null){
            easeConversationListFragment = new EaseConversationListFragment();
            transaction.add(R.id.contain, easeConversationListFragment);
        }
        easeConversationListFragment.setConversationListItemClickListener(new EaseConversationListFragment.EaseConversationListItemClickListener() {
            @Override
            public void onListItemClicked(EMConversation conversation) {

                String username = conversation.conversationId();
                if (username.equals(EMClient.getInstance().getCurrentUser()))
                    Toast.makeText(getActivity(), R.string.Cant_chat_with_yourself, Toast.LENGTH_SHORT).show();
                else {
                    // start chat acitivity
                    Intent intent = new Intent(getActivity(), ChatActivity.class);
                    if(conversation.isGroup()){
                        if(conversation.getType() == EMConversation.EMConversationType.ChatRoom){
                            // it's group chat
                            intent.putExtra(Constant.EXTRA_CHAT_TYPE, Constant.CHATTYPE_CHATROOM);
                        }else{
                            intent.putExtra(Constant.EXTRA_CHAT_TYPE, Constant.CHATTYPE_GROUP);
                        }

                    }
                    // it's single chat
                    intent.putExtra(Constant.EXTRA_USER_ID, username);
                    startActivity(intent);
                }
                //startActivity(new Intent(getActivity(), ChatActivity.class).putExtra(EaseConstant.EXTRA_USER_ID,conversation.conversationId()));
            }
        });
        easeConversationListFragment.refresh();


        //隐藏所有fragment
        hideFragment(transaction);
        //显示需要显示的fragment
        transaction.show(easeConversationListFragment);

        transaction.commit();
    }

    //显示第二个fragment
    private void initFragment2(){
        FragmentTransaction transaction = fm.beginTransaction();

        if(easeContactListFragment == null){
            easeContactListFragment = new ContactListFragment();
            //easeContactListFragment.setContactsMap(getContacts());
            easeContactListFragment.hideTitleBar();
            transaction.add(R.id.contain, easeContactListFragment);

            Map<String, EaseUser> m = DemoHelper.getInstance().getContactList();
            if (m instanceof Hashtable<?, ?>) {
                //noinspection unchecked
                m = (Map<String, EaseUser>) ((Hashtable<String, EaseUser>)m).clone();
            }
            easeContactListFragment.setContactsMap(m);

            easeContactListFragment.setContactListFragmentCallBack(new EaseContactListFragment.ContactListFragmentCallBack() {

                //去新朋友页面
                @Override
                public void gotoNewFriend() {
                    startActivity(new Intent(getActivity() , NewFriendsMsgActivity.class));
                }

                //去群组聊天界面
                @Override
                public void gotoGroup() {
                    startActivity(new Intent(getActivity() , GroupsActivity.class));
                }

                //去添加朋友界面

                @Override
                public void gotoAddFriend() {
                    startActivity(new Intent(getActivity() , AddContactActivity.class));
                }

                //点击listView进入聊天页面
                @Override
                public void gotoChat(EaseUser user) {
                    if (user != null) {
                        String username = user.getNickname();

                        // demo中直接进入聊天页面，实际一般是进入用户详情页
                        startActivity(new Intent(getActivity(), ChatActivity.class).putExtra("userId", username));
                    }
                }
            });
        }
        hideFragment(transaction);
        transaction.show(easeContactListFragment);
        transaction.commit();
    }

    //隐藏所有的fragment
    private void hideFragment(FragmentTransaction transaction){
        if(easeConversationListFragment != null){
            transaction.hide(easeConversationListFragment);
        }
        if(easeContactListFragment != null){
            transaction.hide(easeContactListFragment);
        }
    }

    private void initChatListen(){
        //注册一个监听连接状态的listener
        EMClient.getInstance().chatManager().addMessageListener(messageListener);
    }

    EMMessageListener messageListener = new EMMessageListener() {

        @Override
        public void onMessageReceived(List<EMMessage> messages) {
            // notify new message
            /*for (EMMessage message : messages) {
                DemoHelper.getInstance().getNotifier().onNewMsg(message);
            }*/
            refreshUIWithMessage();
        }

        @Override
        public void onCmdMessageReceived(List<EMMessage> messages) {

        }

        @Override
        public void onMessageRead(List<EMMessage> list) {

        }

        @Override
        public void onMessageDelivered(List<EMMessage> list) {

        }

        @Override
        public void onMessageChanged(EMMessage emMessage, Object o) {

        }
    };

    private void refreshUIWithMessage() {
        getActivity().runOnUiThread(new Runnable() {
            public void run() {
                // refresh unread count
                //updateUnreadLabel();
                // refresh conversation list
                if (easeConversationListFragment != null) {
                    easeConversationListFragment.refresh();
                    easeContactListFragment.refresh();
                }
            }
        });
    }

}
